package com.sixth.aspect;

import com.sixth.bean.MarketFootprint;
import com.sixth.bean.MarketUser;
import com.sixth.mapper.MarketFootprintMapper;
import com.sixth.util.MarketInfoUtil;
import lombok.SneakyThrows;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @ClassName WxUserFootprintAspect
 * @Description TODO
 * @Author XiaoWJ
 * @Date 2022/9/11 20:39
 **/
@Aspect
@Component
public class WxUserFootprintAspect {

    @Autowired
    MarketFootprintMapper marketFootprintMapper;


    // 切入点
    @Pointcut("@annotation(com.sixth.annotation.FootprintAdvice)")
    public void footprintAdvice() {
    }


    // around通知
    @Transactional
    @SneakyThrows
    @Around("footprintAdvice()")
    public Object around(ProceedingJoinPoint joinPoint) {
        MarketFootprint marketFootprint = new MarketFootprint();

        // 获取用户id
        MarketUser marketUser = MarketInfoUtil.getMarketUser();
        if(marketUser == null){
            // 如果用户未登录, 则不增强委托类的方法
            Object proceed = joinPoint.proceed();
            return proceed;
        }
        marketFootprint.setUserId(marketUser.getId());


        // 获取商品id
        // 通过获取委托类的参数
        Object[] args = joinPoint.getArgs();

        for (Object arg : args) {
            if(arg instanceof Integer) {
                marketFootprint.setGoodsId((Integer)arg);
                break;
            }
        }
        // 获取当前时间
        Date date = new Date();

        marketFootprint.setAddTime(date);
        marketFootprint.setUpdateTime(date);

        insertFootprint(marketFootprint);

        // 执行委托类方法
        Object proceed = joinPoint.proceed();

        return proceed;
    }

    private void insertFootprint(MarketFootprint marketFootprint) {

        // 插入历史足迹
        marketFootprintMapper.insertSelective(marketFootprint);

    }

}
